import { defineStore } from 'pinia'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, getInfo, getMyInfo } from '@/api/login'
import { setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			userId: storage.get(constant.userId),
			avatar: storage.get(constant.avatar),
			username: storage.get(constant.username),
			nickname: storage.get(constant.nickname),
			phone: storage.get(constant.phone),
			gender: storage.get(constant.gender) || 2,
			remark: storage.get(constant.remark),
			permissions: storage.get(constant.permissions) || [],
			roles: storage.get(constant.roles) || []
		}
	},
	getters: {
		
	},
	actions: {
		loginAction(data) {
			return new Promise((resolve, reject) => {
				login(data).then(res => {
					setToken(res.result)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		getInfoAction() {
			return new Promise((resolve, reject) => {
				getInfo().then(res => {
					const result = res.result || {}
					if (result.roles && result.roles.length > 0) { // 验证返回的roles是否是一个非空数组
					  this.roles = result.roles
					  this.permissions = result.perms
					} else {
					  this.roles = ['ROLE_DEFAULT']
					}
					storage.set(constant.permissions, this.permissions)
					storage.set(constant.roles, this.roles)
					
					getMyInfo().then(response => {
						let user = response.result || {}
						this.userId = user.userId || ''
						this.avatar = user.avatar || null
						this.username = user.username || ''
						this.nickname = user.nickname || ''
						this.phone = user.phone || ''
						this.gender = user.gender || 2
						this.remark = user.remark || ''
						
						storage.set(constant.userId, this.userId)
						storage.set(constant.avatar, this.avatar)
						storage.set(constant.username, this.username)
						storage.set(constant.nickname, this.nickname)
						storage.set(constant.phone, this.phone)
						storage.set(constant.gender, this.gender)
						storage.set(constant.remark, this.remark)
						resolve(user)
					}).catch(error => {
						reject(error)
					})
				}).catch(error => {
					reject(error)
				})
			})
		},
		logOutAction() {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					removeToken()
					storage.clean()
					this.userId = ''
					this.avatar = ''
					this.username = ''
					this.nickname = ''
					this.phone = ''
					this.gender = ''
					this.remark = ''
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
})